package com.liveHere.www.servlet;

import com.liveHere.www.dao.*;
import com.liveHere.www.po.Room;
import com.liveHere.www.po.Shop;
import com.liveHere.www.po.Order;
import com.liveHere.www.util.JDBCUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author Mo312
 */
public class MerchantServlet {

    private final ShopDao shopDao = new ShopDaoImpl();
    private final OrderDao orderDao = new OrderDaoImpl();
    private final RoomDao roomDao = new RoomDaoImpl();


    public void start() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println();
            System.out.println("-----------------LiveHere Merchant Shop-------------------");
            System.out.println("----------------------------------------------------------");
            System.out.println("1.登录");
            System.out.println("2.注册");
            System.out.println("3.退出");
            System.out.print("\n请输入你的选择：");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 清除缓冲区

            switch (choice) {
                case 1:
                    login();
                    break;
                case 2:
                    register();
                    break;
                case 3:
                    System.out.println("退出系统");
                    return;
                default:
                    System.out.println("无效输入");
            }
        }
    }

    //登录
    public void login() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("\n");
            System.out.print("请输入商铺名: ");
            String username = scanner.nextLine();
            System.out.print("请输入密码: ");
            String password = scanner.nextLine();

            try {
                Shop shop = shopDao.login(username, password);
                if (shop != null) {
                    System.out.println("登录成功\n");
                    shopMenu(shop);
                    break;
                } else {
                    System.out.println("登录失败，请检查商铺名和密码\n");
                }
            } catch (Exception e) {
                System.out.println("登录失败: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    //注册
    public void register() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入商铺名: ");
        String shopName = scanner.nextLine();
        System.out.print("请输入初始密码: ");
        String shopPassword = scanner.nextLine();
        System.out.println("请输入商铺地址：");
        String shopAddress = scanner.nextLine();
        System.out.print("请输入商铺联系方式: ");
        String contact = scanner.nextLine();
        System.out.print("请输入商铺关键词: ");
        String keyword = scanner.nextLine();

        Shop shop = new Shop();
        shop.setShopName(shopName);
        shop.setShopPassword(shopPassword);
        shop.setShopAddress(shopAddress);
        shop.setShopContact(contact);
        shop.setKeywords(keyword);
        shop.setStatus("opening");
        shop.setApplyStatus("pending");
        shop.setDate(java.time.LocalDate.now());


        try {
            shopDao.register(shop);
            System.out.println("注册成功");
        } catch (Exception e) {
            System.out.println("注册失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public void shopMenu(Shop shop) {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println();
            System.out.println("1. 修改店铺信息");
            System.out.println("2. 管理房型");
            System.out.println("3. 查看订单");
            System.out.println("4. 查看营业额");
            System.out.println("5. 退出");
            System.out.print("\n请输入你的选择：");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 清除缓冲区

            switch (choice) {
                case 1:
                    updateShopInfo(shop);
                    break;
                case 2:
                    manageRoomTypes(shop);
                    break;
                case 3:
                    viewOrders(shop);
                    break;
                case 4:
                    viewIncome(shop);
                    break;
                case 5:
                    System.out.println("返回主菜单");
                    return;
                default:
                    System.out.println("无效输入");
            }
        }
    }

    //查看收入
    public void viewIncome(Shop shop) {
        try {
            double income = shopDao.calculateIncome(shop.getShopId());
            System.out.print("\n");
            System.out.println("营业额为: " + income);
        } catch (Exception e) {
            System.out.println("查询营业额失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 修改店铺信息
    public void updateShopInfo(Shop shop) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("\n");
        System.out.print("请输入商铺新名字");
        String shopName = scanner.nextLine();
        System.out.print("请输入新地址: ");
        String newAddress = scanner.nextLine();
        System.out.print("请输入新联系方式: ");
        String newContact = scanner.nextLine();
        System.out.print("请输入新关键词: ");
        String newKeywords = scanner.nextLine();

        shop.setShopName(shopName);
        shop.setShopAddress(newAddress);
        shop.setShopContact(newContact);
        shop.setKeywords(newKeywords);
        try {
            if (shopDao.updateShopInfo(shop)) {
                System.out.println("店铺信息更新成功");
            } else {
                System.out.println("店铺信息更新失败");
            }
        } catch (Exception e) {
            System.out.println("更新店铺信息时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }

    // 管理房型
    public void manageRoomTypes(Shop shop) {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("\n");
            System.out.println("1. 增加房型");
            System.out.println("2. 删除房型");
            System.out.println("3. 查询房型");
            System.out.println("4. 修改房型");
            System.out.println("5. 返回");
            System.out.print("\n请输入你的选择：");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 清除缓冲区

            switch (choice) {
                case 1:
                    // 添加房型逻辑
                    addRooms(shop);
                    break;
                case 2:
                    // 删除房型逻辑
                    queryRooms(shop.getShopId());
                    System.out.println("\n");
                    deleteRoomType();
                    break;
                case 3:
                    // 查询房型逻辑
                    queryRooms(shop.getShopId());
                    break;
                case 4:
                    // 修改房型逻辑
                    queryRooms(shop.getShopId());
                    System.out.println("\n");
                    updateRoomType();
                    break;
                case 5:
                    return;
                default:
                    System.out.println("无效输入");
            }
        }
    }

    // 增加房型
    public void addRooms(Shop shop) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("\n");
        System.out.print("请输入房间名称：");
        String roomName = scanner.nextLine();
        System.out.println("请输入房间类型：（几人）");
        String roomType = scanner.nextLine();
        System.out.println("请输入房间关键词：");
        String keywords = scanner.nextLine();
        System.out.print("请输入房型价格：");
        double price = scanner.nextDouble();
        System.out.print("请输入房型数量：");
        int remaining = scanner.nextInt();

        scanner.nextLine();

        Room room = new Room();
        room.setShopId(shop.getShopId());
        room.setRoomName(roomName);
        room.setRoomType(roomType);
        room.setKeywords(keywords);
        room.setPrice(price);
        room.setRemaining(remaining);

        System.out.print("\n");
        try {
            boolean success = roomDao.addRoom(room);
            if (success) {
                System.out.println("房型添加成功！");
            } else {
                System.out.println("房型添加失败！");
            }
        } catch (Exception e) {
            System.out.println("添加房型时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }

    // 删除房型
    public void deleteRoomType() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("\n请输入房型ID：");
        int roomId = scanner.nextInt();
        scanner.nextLine(); // 清除缓冲区

        System.out.print("\n");
        try {
            boolean success = roomDao.deleteRoom(roomId);
            if (success) {
                System.out.println("房型删除成功！");
            } else {
                System.out.println("房型删除失败！");
            }
        } catch (Exception e) {
            System.out.println("删除房型时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }

    // 查询房间
    private void queryRooms(int shopId) {
        try {
            List<Room> rooms = roomDao.getRoomsByShopId(shopId);
            if (rooms.isEmpty()) {
                System.out.println("\n暂无房间信息！");
            } else {
                System.out.println("\n房间信息：");
                System.out.print("\n");
                for (Room room : rooms) {
                    System.out.println("房间ID: " + room.getRoomId());
                    System.out.println("房间名称: " + room.getRoomName());
                    System.out.println("房型（床型）: " + room.getRoomType());
                    System.out.println("关键词: " + room.getKeywords());
                    System.out.println("剩余数量: " + room.getRemaining());
                    System.out.println("价格：" + room.getPrice());
                    System.out.println("-------------------------------");
                }
            }
        } catch (Exception e) {
            System.out.println("查询房型时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }

    // 修改房型
    private void updateRoomType() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("\n请输入房型ID：");
        int roomId = scanner.nextInt();
        scanner.nextLine();

        System.out.print("\n");
        System.out.print("请输入新的房型名称：");
        String roomNewName = scanner.nextLine();
        System.out.print("请输入新的房间类型：");
        String roomType = scanner.nextLine();
        System.out.print("请输入新的房间关键词：");
        String newKeywords = scanner.nextLine();
        System.out.print("请输入新的房型价格：");
        double newPrice = scanner.nextDouble();
        System.out.print("请输入新的房间数量：");
        int newRemaining = scanner.nextInt();
        scanner.nextLine();

        Room room = new Room();
        room.setRoomId(roomId);
        room.setRoomName(roomNewName);
        room.setRoomType(roomType);
        room.setKeywords(newKeywords);
        room.setPrice(newPrice);
        room.setRemaining(newRemaining);

        System.out.print("\n");
        try {
            boolean success = roomDao.updateRoom(room);
            if (success) {
                System.out.println("房型修改成功！");
            } else {
                System.out.println("房型修改失败！");
            }
        } catch (Exception e) {
            System.out.println("修改房型时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }

    // 订单相关
    public void viewOrders(Shop shop) {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("1. 查看订单");
            System.out.println("2. 查询并修改待核销订单状态");
            System.out.println("3. 返回");
            System.out.print("\n请输入你的选择：");
            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    // 查询所有订单
                    viewOrderList(shop.getShopId());
                    break;
                case 2:
                    // 查询并修改待核销订单状态
                    changeOrderStatus(shop);
                    break;
                case 3:
                    return;
                default:
                    System.out.println("无效输入");
            }
        }
    }

    // 查询所有订单
    public void viewOrderList(int shopId) {
        try {
            ArrayList<Order> orders = orderDao.getOrderListByShopId(shopId);

            System.out.print("\n");
            if (orders == null || orders.isEmpty()) {
                System.out.println("无订单");
            } else {
                System.out.println("订单信息如下");
                System.out.print("\n");
                for (Order order : orders) {
                    System.out.println("店铺名字：" + order.getShopName());
                    System.out.println("订单ID: " + order.getOrderId());
                    System.out.println("用户ID: " + order.getUserId());
                    System.out.println("用户名: " + order.getUsername());
                    System.out.println("房间名称：" + order.getRoomName());
                    System.out.println("房间类型：" + order.getRoomType());
                    System.out.println("入住时间：" + order.getCheckInDate());
                    System.out.println("退房时间：" + order.getCheckOutDate());
                    System.out.println("房间状态：" + order.getStatus());
                    System.out.println("订单金额：" + order.getPrice());
                    System.out.println("-------------------------------");

                }
            }
        } catch (Exception e) {
            System.out.println("查询订单时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }

    // 查询并修改待核销订单状态
    public void changeOrderStatus(Shop shop) {
        Scanner scanner = new Scanner(System.in);
        Connection conn = null;
        try {
            // 获取连接并开启事务
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);

            List<Order> orders = orderDao.getOrdersByStatusAndShopId("待核销", shop.getShopId());
            if (orders.isEmpty()) {
                System.out.println("暂无符合条件的订单！");
                return;
            } else {
                System.out.print("\n");
                System.out.println("订单:");
                for (Order order : orders) {
                    System.out.println("店铺名字：" + order.getShopName());
                    System.out.println("订单ID: " + order.getOrderId());
                    System.out.println("用户ID: " + order.getUserId());
                    System.out.println("用户名: " + order.getUsername());
                    System.out.println("房间名称：" + order.getRoomName());
                    System.out.println("房间类型：" + order.getRoomType());
                    System.out.println("入住时间：" + order.getCheckInDate());
                    System.out.println("退房时间：" + order.getCheckOutDate());
                    System.out.println("房间状态：" + order.getStatus());
                    System.out.println("订单金额：" + order.getPrice());
                    System.out.println("-------------------------------");

                }
            }

            System.out.print("\n请输入订单号：");
            int orderId = scanner.nextInt();
            scanner.nextLine();
            System.out.print("\n请输入新的订单状态（如：已核销）：");
            String newStatus = scanner.nextLine();
            scanner.nextLine();

            //增加收入
            Order selectedOrder = orderDao.getOrderById(orderId);
            if (("已核销").equals(newStatus)) {
                double newIncome = shop.getIncome() + selectedOrder.getPrice();
                shop.setIncome(newIncome);
                shopDao.updateShopIncome(shop.getShopId(), newIncome);
            }

            // 更新订单状态
            boolean success = orderDao.updateOrderStatus(orderId, newStatus);
            if (success) {
                System.out.println("订单状态更新成功！");
                // 提交事务
                conn.commit();
            } else {
                System.out.println("订单状态更新失败！");
                // 回滚事务
                conn.rollback();
            }
        } catch (Exception e) {
            // 发生异常时回滚事务
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            System.out.println("更新订单状态时发生错误：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 关闭连接
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
